package com.jt.safe.base

import android.app.Dialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.IBinder
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.blankj.utilcode.util.KeyboardUtils
import com.dueeeke.videoplayer.player.AbstractPlayer
import com.gyf.immersionbar.ktx.immersionBar
import com.jt.safe.R
import com.jt.safe.config.Config
import com.jt.safe.extension.getVmClazz
import com.jt.safe.utils.ActivityAdmin
import com.jt.safe.viewmodel.BaseViewModel

abstract class BaseActivity<VM : BaseViewModel> : AppCompatActivity() {

    private var mDialog: Dialog? = null
    lateinit var viewModel: VM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layoutId)
        ActivityAdmin.instance.addActivity(this)
        viewModel = createViewModel()
        createObserver()
        immersionBar {
            statusBarColor(R.color.white)
            statusBarDarkFont(true, 0.2f)
            fitsSystemWindows(true)
        }
        initView()
    }

    @get:LayoutRes
    protected abstract val layoutId: Int

    abstract fun initView()

    private fun createViewModel(): VM {
        return ViewModelProviders.of(this).get(getVmClazz(this) as Class<VM>)
    }

    protected abstract fun createObserver()

    fun showProgress() {
        if (mDialog == null) {
            mDialog = Dialog(this)
            mDialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
            val progressBar = ProgressBar(this)
            progressBar.indeterminateDrawable =
                    ContextCompat.getDrawable(this, R.drawable.progressbar)
            mDialog?.setContentView(progressBar)
        }
        mDialog?.show()
    }

    fun dismissProgress() {
        mDialog?.dismiss()
        mDialog = null
    }

    fun showToast(message: String?) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {

            if (isShouldHideKeyboard(currentFocus, ev)) {
                hideKeyboard(currentFocus?.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if ((v is EditText)) {
            val intArrayOf = intArrayOf(0, 0)
            v.getLocationInWindow(intArrayOf)
            val left = intArrayOf[0]
            val top = intArrayOf[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right
                    && event.y > top && event.y < bottom)
        }
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            KeyboardUtils.hideSoftInput(this)
        }
    }


    override fun onResume() {
        super.onResume()
        registerMessageReceiver()
    }

    override fun onPause() {
        super.onPause()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver)
    }

    //for receive customer msg from jpush server
    lateinit var mMessageReceiver: MessageReceiver

    private fun registerMessageReceiver() {
        mMessageReceiver = MessageReceiver()
        val filter = IntentFilter()
        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        filter.addAction(Config.MESSAGE_RECEIVED_ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter)
    }

    inner class MessageReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (Config.MESSAGE_RECEIVED_ACTION == intent.action) {
//                val message = intent.getStringExtra(Config.KEY_MESSAGE)
                val extras = intent.getStringExtra(Config.KEY_EXTRAS)
                val alert = intent.getStringExtra(Config.ALERT)
//                val fromJson =
//                        Gson().fromJson<AnnouncementJpush>(extras, AnnouncementJpush::class.java)
//                if (fromJson.type == "1") {
//                    showAnnouncement(fromJson.communityId, alert)
//                }

            }
        }

        private fun showAnnouncement(communityId: String, alert: String) {
            MaterialDialog(this@BaseActivity).show {
                customView(R.layout.announcement_dialog)
                val customView = getCustomView()
                val byId = customView.findViewById<TextView>(R.id._true)
                val title = customView.findViewById<TextView>(R.id.title)
                title.text = alert
                byId.setOnClickListener {
                    dismiss()
                }
                val byId1 = customView.findViewById<TextView>(R.id._false)
                byId1.setOnClickListener { dismiss() }
            }
        }

    }
}